const { StuModel, classModel } = require("../model/index");
function checkSameClassName(stuList) {
  // 假设 stuList 是一个有效的 JSON 数组，并且每个对象都有一个 className 字段
  if (!Array.isArray(stuList) || stuList.length === 0) {
    return false; // 如果 stuList 不是数组或为空，返回 false
  }

  // 获取第一个对象的 className 作为基准
  let firstClassName = stuList[0].className;

  // 遍历数组检查所有对象的 className 是否与基准相同
  for (let i = 1; i < stuList.length; i++) {
    if (stuList[i].className !== firstClassName) {
      // 如果发现不同的 className，直接返回 false
      return false;
    }
  }

  // 如果所有 className 都相同，返回 true
  return true;
}
// 添加学生(单个)
exports.addStudent = async (req, res) => {
  const { stuNum, stuName, jobId, className, submitNum, isReading, password } =
    req.body;
  if (!stuNum || !stuName || !jobId || !className) {
    return res.status(400).json({
      code: 400,
      message: "参数不完整",
      data: null,
    });
  }
  try {
    let stundet = await StuModel.findOne({ stuNum });
    if (stundet) {
      return res.status(400).json({
        code: 400,
        message: "学生已存在",
        data: null,
      });
    }
    let dbBack = new StuModel({
      stuNum,
      stuName,
      jobId,
      className,
      submitNum,
      isReading,
      password: password ? password : "123456",
    });
    await dbBack.save();
    let classInfo = await classModel.findOne({ className });
    if (classInfo) {
      classInfo.classNumber++;
      await classInfo.save();
    }
    return res.status(200).json({
      code: 200,
      message: "添加成功",
      data: null,
    });
  } catch (error) {
    return res.status(500).json({
      code: 500,
      message: "服务器错误" + error.message,
      data: null,
    });
  }
};
//添加多个学生
exports.addStudentBatch = async (req, res) => {
  const { stuList } = req.body;
  if (!stuList) {
    return res.status(400).json({
      code: 400,
      message: "参数不完整",
      data: null,
    });
  }
  if (stuList.length === 0) {
    return res.status(400).json({
      code: 400,
      message: "学生列表不能为空",
      data: null,
    });
  }
  try {
    let dbStudent = await StuModel.find();
    // 使用 some 替代 forEach 来检查是否有重复的学号
    const hasDuplicate = stuList.some((newItem) => {
      return dbStudent.some((existingItem) => {
        return newItem.stuNum == existingItem.stuNum;
      });
    });

    if (hasDuplicate) {
      // 如果存在重复学号，直接发送响应并退出函数
      return res.status(400).json({
        code: 400,
        message: "存在重复的学号",
        data: null,
      });
    }
    //判断班级是否存在
    let ClassInfo = await classModel.find();
    //判断stuList中的班级是否在classInfo中存在
    let classList = stuList.map((item) => item.className);
    let classExist = classList.every((item) =>
      ClassInfo.some((item2) => item2.className == item)
    );
    if (!classExist) {
      return res.status(400).json({
        code: 400,
        message: "部分班级不存在，请创建好对应班级后再添加学生",
        data: null,
      });
    }
    let isCf = checkSameClassName(stuList);
    if (!isCf) {
      return res.status(400).json({
        code: 400,
        message: "学生列表中的班级必须相同",
        data: null,
      });
    }
    let count = stuList.length;
    let classInfo = await classModel.findOne({className:stuList[0].className});
    if(classInfo){
      classInfo.classNumber+=count;
      await classInfo.save();
    }else {
      return res.status(400).json({
        code: 400,
        message: "班级不存在",
        data: null,
      });
    }
    // 如果没有重复学号，则批量添加
    await StuModel.insertMany(stuList);
    return res.status(200).json({
      code: 200,
      message: "添加成功",
      data: null,
    });
  } catch (error) {
    // 捕获并处理错误
    return res.status(500).json({
      code: 500,
      message: "服务器错误: " + error.message, // 最好只发送错误消息，而不是整个错误对象
      data: null,
    });
  }
};
//查询学生列表
exports.getStudentList = async (req, res) => {
  const { pageNo = 1, pageSize = 10, className = "", stuName = "" } = req.query;
  try {
    let result = await StuModel.find({
      className: { $regex: className, $options: "i" },
      stuName: { $regex: stuName, $options: "i" },
    })
      .skip((pageNo - 1) * pageSize)
      .limit(pageSize)
      .sort({ stuNum: 1 })
      .populate("jobId");
    let count = await StuModel.find({
      className: { $regex: className, $options: "i" },
      stuName: { $regex: stuName, $options: "i" },
    }).count();
    return res.status(200).json({
      code: 200,
      message: "查询成功",
      data: {
        list: result,
        count,
      },
    });
  } catch (error) {
    return res.status(500).json({
      code: 500,
      message: "服务器错误",
      data: null,
    });
  }
};
//获取学生详情
exports.getStudentDetail = async (req, res) => {
  let { stuId } = req.query;
  if (!stuId) {
    return res.status(400).json({
      code: 400,
      message: "参数不完整",
      data: null,
    });
  }
  try {
    let result = await StuModel.findById(stuId).populate("jobId");
    return res.status(200).json({
      code: 200,
      message: "查询成功",
      data: result,
    });
  } catch (error) {
    return res.status(500).json({
      code: 500,
      message: "服务器错误",
      data: null,
    });
  }
};
//修改学生信息
exports.updateStudent = async (req, res) => {
  let stuId = req.query.stuId;
  let { stuName, stuNum, className, jobId, submitNum, isReading, password } =
    req.body;
  console.log(
    stuId,
    stuName,
    stuNum,
    className,
    jobId,
    submitNum,
    isReading,
    password
  );
  if (
    !stuId ||
    !stuName ||
    !stuNum ||
    !className ||
    !isReading ||
    !password ||
    !jobId
  ) {
    return res.status(400).json({
      code: 400,
      message: "参数不完整",
      data: null,
    });
  }
  try {
    let result = await StuModel.findByIdAndUpdate(stuId, {
      stuName,
      stuNum,
      className,
      jobId,
      submitNum,
      isReading,
      password,
    });
    return res.status(200).json({
      code: 200,
      message: "修改成功",
      data: result,
    });
  } catch (error) {
    return res.status(500).json({
      code: 500,
      message: "服务器错误",
      data: null,
    });
  }
};
//删除学生(对应班级的人数要-1)
exports.deleteStudent = async (req, res) => {
  let stuId = req.query.stuId;
  if (!stuId) {
    return res.status(400).json({
      code: 400,
      message: "参数不完整",
      data: null,
    });
  }
  try {
    let result = await StuModel.findOne({ _id: stuId });
    if (!result) {
      return res.status(400).json({
        code: 400,
        message: "该学生不存在",
        data: null,
      });
    }
    await StuModel.findByIdAndDelete(stuId);

    let className = result.className;
    let classInfo = await classModel.findOne({ className: className });
    classInfo.classNumber--;
    await classInfo.save();
    return res.status(200).json({
      code: 200,
      message: "删除成功",
      data: null,
    });
  } catch (error) {
    return res.status(500).json({
      code: 500,
      message: "服务器错误",
      data: null,
    });
  }
};
